#!/usr/bin/env python
# server.py

import asyncore
import logging
import threading
import signal
import sys

from tools import polling
from tools import config
from tools import parser

config.init()

exec "from net." + config.getNetBackend() + " import *"

nodes = config.getNodeList()
nodes_and_conns = [[], [], [], [[],[]], []]

def handle_signal (signum, frame) :
	sys.exit ("Terminating.")

def run () :
	signal.signal(signal.SIGINT, handle_signal)
	signal.signal(signal.SIGTERM, handle_signal)
	pars = parser.ParserClass (nodes_and_conns)
	for node in nodes :
		n_idx = -1
		for n in nodes_and_conns[1] :
			if n.addr == node[1] :
				n_idx = nodes_and_conns[1].idx (n)
		nodes_and_conns[0].append (node[0])
		cond = threading.Condition ()
		nodes_and_conns[4].append (cond)
		if n_idx == -1 :
			nodes_and_conns[1].append (Conn (node, pars))
		else :
			nodes_and_conns[1].append (nodes_and_conns[1][n_idx])
		nodes_and_conns[2].append (config.getSimplePlugins (node[0]))
		nodes_and_conns[3][0].append (config.getBufPlugins (node[0]))
		nodes_and_conns[3][1].append ([])
		for plug in nodes_and_conns[3][0][-1] :
			nodes_and_conns[3][1][-1].append (0)
	simplepoll = polling.PollThread (nodes_and_conns)
	simplepoll.start ()
	buffpoll = polling.BPollThread (nodes_and_conns)
	buffpoll.start ()
	asyncore.loop ()
	buffpoll.join ()
	simplepoll.join ()

if __name__ == "__main__" :
	run ()

